/**
 * WxApi
 * @Author Ace.c
 * @Create 2016-11-03 16:21
 */
class Weixin {
    //注册分享的时刻点
    static onShare_time: any = {
        game_main: false,//游戏主界面上注册
        in_room: false,//收到8号消息房间内注册
        wx_ready: false,
    };

    //分享地址
    static shareUrl(type: number = -1, circle_join?: string): string {
        let url: string = GameConfig.clientUrl + "?v=" + Math.random();

        if (game.ip) url += "&ip=" + game.ip;
        if (game.port) url += "&port=" + game.port;
        if (game.branch) url += "&branch=" + game.branch;

        switch (type) {
            case 1://房间
                if (circle_join) {
                    url += circle_join;
                    break;
                } else if (game.search && game.search.circle) {
                    url += "&circle=" + game.search.circle;
                }
                if (game.roomid) url += "&roomid=" + game.roomid;
                if (game.roomCreateTime) url += "&createtime=" + game.roomCreateTime;

                break;
            case 2://回放
                url += "&uid=" + Replayer.shareIF.uid;
                url += "&item_id=" + Replayer.shareIF.item_id;
                url += "&playback_id=" + Replayer.shareIF.playback_id;
                break;
        }

        return url;
    }

    //获取授权code
    static getAccessCode(appid: string, url: string) {
        location.href = "" +
            "https://open.weixin.qq.com/connect/oauth2/authorize?" +
            "appid=" + appid +
            "&redirect_uri=" + encodeURIComponent(url) +
            "&response_type=code" +
            "&scope=snsapi_userinfo" +
            "&state=1" +
            "#wechat_redirect";
    }

    //微信权限验证
    static config(appid: string, timestamp: number, nonceStr: string, signature: string, jsApiList: string[] = []) {
        let bodyConfig: BodyConfig = new BodyConfig();
        bodyConfig.appId = appid;
        bodyConfig.debug = false;
        bodyConfig.timestamp = +timestamp;
        bodyConfig.nonceStr = nonceStr;
        bodyConfig.signature = signature;
        bodyConfig.jsApiList = jsApiList;

        if (wx) {
            wx.config(bodyConfig);

            wx.ready(function () {
                Weixin.hideMenuItems();

                // Weixin.shareGame();
                // Weixin.shareGameToTimeline();

                Weixin.getLocation();

                Weixin.onShare_time.wx_ready = true;
            });
        }
    }

    //获取地理位置
    static getLocation() {
        console.log('地理位置信息------------1');

        //TODO 测试
        if (game.user) {
            game.poswx = Math.random() + "," + Math.random();

            game.poswx && gameManager.socketManager.send(501, { pos: game.poswx });
            gameManager.i.dispatchEvent(GameEventType.UPDATE_LOCATION);
        }

        wx.getLocation({
            type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
            success: function (res) {
                if (res.errMsg != 'getLocation:ok') {
                    EffectTextUtils.showTips('暂不能使用测距功能，请稍后再试');
                    return;
                }

                game.latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
                game.longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
                game.speed = res.speed; // 速度，以米/每秒计
                game.accuracy = res.accuracy; // 位置精度

                game.poswx = game.latitude + "," + game.longitude;

                console.log('地理位置信息------------2');
                console.log(res);

                Weixin.sendPos();
            },
            fail: function (res) {
                EffectTextUtils.showTips('必须先授权定位，才能使用测距功能');
            },
            cancel: function (res) {
                EffectTextUtils.showTips('未授权定位，将不能使用测距功能');
            },
            error: function (res) {
                EffectTextUtils.showTips('测距功能开启失败');
            }
        });
    }

    //发送位置
    static sendPos() {
        if (game.poswx) {
            if (+GameStorage.getData(GameStorage.first) != new Date().getUTCDate()) {
                gameManager.socketManager.send(409, { pos: game.poswx });
            }

            gameManager.socketManager.send(501, { pos: game.poswx });

            gameManager.i.dispatchEvent(GameEventType.UPDATE_LOCATION);
        }
    }

    //支付
    static pay(timestamp: number, nonceStr: string, prepay_id: string, paySign: string, success?: Function) {
        wx.checkJsApi({
            jsApiList: ['chooseWXPay'],
            success: function () {
                wx.chooseWXPay({
                    timestamp: timestamp,
                    nonceStr: nonceStr,
                    package: prepay_id,
                    paySign: paySign,
                    signType: "MD5",
                    success: success
                });
            }
        });
    }

    //关闭游戏窗口返回微信
    static closeWindow() {
        let body: BodyConfig = new BodyConfig();
        wx.closeWindow(body);
    }


    //分享游戏到朋友圈
    static shareGameToTimeline(roomid: string = null, daikai: boolean = false) {
        let body: BodyMenuShareTimeline = new BodyMenuShareTimeline();

        body.title = "【" + GameConfig.mahjong_name + "】无需下载，点击开战！";

        if (+roomid > 1000) {
            body.link = this.shareUrl(1);
        }
        else {
            body.link = this.shareUrl();
        }

        body.imgUrl = daikai ? GameConfig.daikaiShareIconUrl : GameConfig.shareIconUrl;
        body.success = function () {
            game.share.hide();
        };
        body.cancel = function () {
            game.share.hide();
        };
        wx.onMenuShareTimeline(body);

        console.log('===========分享到朋友圈==========');
        console.log(body);
    }

    //分享游戏到朋友
    static shareGame(roomid: string = null, daikai: boolean = false) {
        let body: BodyMenuShareAppMessage = new BodyMenuShareAppMessage();

        if (+roomid > 1000) {
            body.title = "" +
                (game.isRoomOwner ? "【房主】" : "") + game.player.nick + "" +
                "邀请你加入房间:" + (roomid.split("").join(' ')) + "-" +
                "【" + GameConfig.mahjong_name + "】";

            body.link = this.shareUrl(1);

            body.desc = "" +
                '【' +
                game.roomSeat + "" +
                '人' +
                (game.roomRoundType == RoundType.quan ? game.roomRound / 4 : game.roomRound) +
                (game.roomRoundType == RoundType.quan ? '圈' : '局') +
                '】' +
                game.ruleTexts();
        }
        else {
            body.title = "【" + GameConfig.mahjong_name + "】无需下载，点击开战！";
            body.desc = "私房麻将馆，好友组局，微信登录，玩牌交友两不误！";
            body.link = this.shareUrl();
        }

        body.imgUrl = daikai ? GameConfig.daikaiShareIconUrl : GameConfig.shareIconUrl;
        body.dataUrl = "";
        body.success = function () {
            game.share.hide();
        };
        body.cancel = function () {
            game.share.hide();
        };

        wx.onMenuShareAppMessage(body);

        console.log('===========分享到朋友==========');
        console.log(body);
    }

    //分享总结算
    static shareScore(fenlist: any[]) {
        let title: string = "大赢家-";
        let desc: string = "";
        let imgUrl: string;

        if (game.isDaikai) {
            imgUrl = GameConfig.daikaiShareIconUrl
        } else {
            switch (game.roomState) {
                case RoomState.CIRCLE:
                    imgUrl = GameConfig.circleShareIconUrl;
                    break;
                default:
                    imgUrl = GameConfig.shareIconUrl;
                    break;
            }
        }

        if (fenlist && fenlist.length > 0) {
            fenlist.sort(function (a: any, b: any) {
                return +a.cur > +b.cur ? -1 : 1;
            });

            let person;
            for (let i = 0; i < fenlist.length; i++) {
                person = fenlist[i];
                if (i == 0) {
                    title += (person.pos == 1 ? "【房主】" : "") + person.nick + ":" + person.cur + "分";
                }
                else {
                    desc += (person.pos == 1 ? "【房主】" : "") + person.nick + ":" + person.cur + "分";
                }
            }
        }

        let body: BodyMenuShareAppMessage = new BodyMenuShareAppMessage();
        body.title = title;
        body.desc = desc;
        body.link = this.shareUrl();
        body.imgUrl = imgUrl;
        body.dataUrl = "";
        body.success = function () {
            game.share.hide();
        };
        body.cancel = function () {
            game.share.hide();
        };
        wx.onMenuShareAppMessage(body);

        console.log('===========分享总结算==========');
        console.log(body);
    }

    //分享回放
    static shareReplay(replayType: ReplayShare = undefined) {
        let imgUrl: string;
        switch (replayType) {
            case ReplayShare.CIRCLE:
                imgUrl = GameConfig.circleShareIconUrl;
                break;
            default:
                imgUrl = GameConfig.replayShareIconUrl;
                break;
        }

        game.share.show();

        let body: BodyMenuShareAppMessage = new BodyMenuShareAppMessage();

        body.title = "牌局回放-【" + GameConfig.mahjong_name + "】";
        body.desc = Replayer.shareIF.share_desc;
        body.link = this.shareUrl(2);
        body.imgUrl = imgUrl;
        body.dataUrl = "";
        body.success = function () {
            game.share.hide();
        };
        body.cancel = function () {
            game.share.hide();
        };

        wx.onMenuShareAppMessage(body);

        console.log('===========分享战斗回放==========');
        console.log(body);
    }

    //隐藏微信菜单按钮
    static hideMenuItems() {
        wx.hideMenuItems({
            "menuList": [
                "menuItem:share:timeline",
                "menuItem:share:qq",
                "menuItem:share:weiboApp",
                "menuItem:share:facebook",
                "menuItem:share:QZone",
                "menuItem:share:timeline",
                "menuItem:editTag",
                "menuItem:delete",
                "menuItem:copyUrl",
                "menuItem:originPage",
                "menuItem:readMode",
                "menuItem:openWithQQBrowser",
                "menuItem:openWithSafari",
                "menuItem:share:email",
                "menuItem:favorite",
                "menuItem:share:brand"
            ]
        });
    }

    //开始录音接口
    static startRecord() {
        let body: BodyConfig = new BodyConfig();
        wx.startRecord(body);
    }

    //停止录音接口
    static stopRecord() {
        wx.stopRecord({
            success: function (res) {
                let localId = res.localId;

                Weixin.uploadVoice(localId);
            }
        });
    }

    //监听录音自动停止接口
    static onVoiceRecordEnd() {
        wx.onVoiceRecordEnd({
            // 录音时间超过一分钟没有停止的时候会执行 complete 回调
            complete: function (res) {
                let localId = res.localId;
                Weixin.uploadVoice(localId);
                GameOthers.hideVoice();
            }
        });
    }

    //播放语音接口
    static playVoice(localId: string) {
        wx.playVoice({
            localId: localId // 需要播放的音频的本地ID，由stopRecord接口获得
        });
    }

    //暂停播放接口
    static pauseVoice(localId: string) {
        wx.pauseVoice({
            localId: localId // 需要暂停的音频的本地ID，由stopRecord接口获得
        });
    }

    //停止播放接口
    static stopVoice(localId: string) {
        wx.stopVoice({
            localId: localId // 需要停止的音频的本地ID，由stopRecord接口获得
        });
    }

    //监听语音播放完毕接口
    static onVoicePlayEnd() {
        wx.onVoicePlayEnd({
            success: function (res) {
                let localId = res.localId; // 返回音频的本地ID
            }
        });
    }

    //上传语音接口
    static uploadVoice(localId: string) {
        wx.uploadVoice({
            localId: localId, // 需要上传的音频的本地ID，由stopRecord接口获得
            isShowProgressTips: 0, // 默认为1，显示进度提示
            success: function (res) {
                let serverId = res.serverId; // 返回音频的服务器端ID

                gameManager.socketManager.send(25, { type: 2, voice: { id: serverId } });
            }
        });
    }

    //下载语音接口
    static downloadVoice(localId: string) {
        wx.downloadVoice({
            serverId: localId, // 需要下载的音频的服务器端ID，由uploadVoice接口获得
            isShowProgressTips: 0, // 默认为1，显示进度提示
            success: function (res) {
                let localId = res.localId; // 返回音频的本地ID

                Weixin.playVoice(localId);
            }
        });
    }

    //圈子内的加入房间分享
    static onCircleJoinShare() {

        if (!Weixin.onShare_time.wx_ready) console.log("-----微信接口没准备好-----");

        function success() {
            game.share.hide();
        }

        function cancel() {
            game.share.hide();
        }

        var circle_link_args = Circle.circle_link.get_str(Circle.args_2017);
        console.log("circle_link_args : ", circle_link_args);

        var body: BodyMenuShareAppMessage = new BodyMenuShareAppMessage();
        body.title = Circle.circle_share_title.replace("1%", Circle.circle_data.zhu_name);
        body.desc = Circle.circle_share_des.replace("1%", Circle.args_2017.id);
        body.link = Weixin.shareUrl(1, circle_link_args);
        body.imgUrl = "" + GameConfig.circleShareIconUrl;
        body.dataUrl = "";
        body.success = success;
        body.cancel = cancel;
        wx.onMenuShareAppMessage(body);
        console.log("onCircleJoinShare", body);

    }

    static circleShareGameToTimeline() {
        let body: BodyMenuShareTimeline = new BodyMenuShareTimeline();
        var circle_link_args = Circle.circle_link.get_str(Circle.args_2017);
        body.title = "【" + GameConfig.mahjong_name + "】无需下载，点击开战！";

        body.link = Weixin.shareUrl(1, circle_link_args);

        body.imgUrl = GameConfig.circleShareIconUrl;
        body.success = function () {
            game.share.hide();
        };
        body.cancel = function () {
            game.share.hide();
        };
        wx.onMenuShareTimeline(body);

        console.log('===========老友圈分享到朋友圈==========');
        console.log(body);
    }

}